#include "DeadProxyLaunchClient.h"
#include "windows.h"
#include <stdio.h>

#include "DeadProxyApp.h"

LaunchClientThread::LaunchClientThread(const char * command, const char * workingdirectory)
{
    com = command;
    dir = workingdirectory;
}

void * LaunchClientThread::Entry()
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Start the child process.
    if(CreateProcess( NULL,   // No module name (use command line)
        (char *)com,//"\"C:\\Program Files\\Tibia\\Tibia.exe\"",        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        TRUE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        (char *)dir,//"C:\\Program Files\\Tibia",           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        Sleep(1000);
        app->AddClient(pi.dwProcessId, pi.hProcess, false);
    } else {
        return 0;
    }
    //Delete strings, no further use
    //delete[] com;
    //delete[] dir;
    
    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, INFINITE );

    // Add Client Removal Code here
    //
        app->RemoveClient(pi.dwProcessId);
    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    
    return 0;
}

void LaunchClientThread::OnExit()
{
}
